import React, { useEffect, useState, useMemo } from "react";
// import axios from "axios";
// import http from "@/utils/http";
import { cityApi } from "@/api/city";
import { useNavigate } from "react-router-dom";

import "./index.less";

import { useDispatch } from "react-redux";
import { changeName } from "../../store/modules/city";

const Index = () => {
  const [cityList, setCityList] = useState([]);
  const dispatch = useDispatch();
  const na = useNavigate();

  useEffect(() => {
    // axios
    //   .get("http://www.pudge.wang:3080/api/area/list")
    //   .then((response) => {
    //     setCityList(response.data.result);
    //   })
    //   .catch((error) => {
    //     console.log(error);
    //   });

    // http.get("http://www.pudge.wang:3080/api/area/list").then((res) => {
    //   setCityList(res.data.result);
    // });

    // cityApi({ a: 3 }).then((res) => {
    //   setCityList(res.data.result);
    // })

    (async () => {
      try {
        const res = await cityApi({ a: 3 });
        setCityList(res.result);
      } catch (err) {
        console.log(err);
      }

      // try {
      //   console.log(a);
      // } catch (err) {
      //   console.log(456);
      // }
    })();
  }, []);

  const hotCity = useMemo(() => {
    return cityList[0];
  }, [cityList]);

  const otherCity = useMemo(() => {
    return cityList.slice(1);
  }, [cityList]);

  const goHome = (name) => {
    dispatch(changeName({ name }));
    na(-1);
  };

  return (
    cityList.length && (
      <div>
        <div className="citytitle">{hotCity.prefix}</div>
        <ul>
          {hotCity.cities.map((value) => {
            return (
              <li key={value.cityId} className="cityli">
                {value.name}
              </li>
            );
          })}
        </ul>

        {otherCity.map((item) => {
          return (
            <div key={item.prefix}>
              <div className="citytitle">{item.prefix}</div>
              <ul>
                {item.cities.map((value) => {
                  return (
                    <li
                      key={value.cityId}
                      className="cityli"
                      onClick={() => goHome(value.name)}
                    >
                      {value.name}
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        })}
      </div>
    )
  );
};

export default Index;
